defmodule Club.ActivityAdapter do
    
    alias Club.Repo
    alias Club.Activity

    require Ecto.Query
    require Logger

    def create(params) do

        starttime = params.starttime
        endtime = params.endtime

        {:ok, sdt} = DateTime.from_unix(starttime)
        st = DateTime.to_naive(sdt)

        {:ok, edt} = DateTime.from_unix(endtime)
        et = DateTime.to_naive(edt)

        params = params
                |> Map.put(:starttime, st)
                |> Map.put(:endtime, et)
                
        changeset = Activity.changeset(%Activity{}, params)

        case changeset.valid? do
            true ->
                case Repo.insert(changeset) do
                    {:ok, activity} ->
                        activity
                    {:error, msg} ->
                        nil
                        # errormsg = SchemaClub.getErrorMsg(msg.errors, %{})
                end
            false ->
                # errormsg = SchemaClub.getErrorMsg(changeset.error, %{})    #返回错误消息
                nil
        end
    end

    def get_info_activity(id) when is_integer(id) do
        Activity
        |> Repo.get(id)
    end

    def get_club_activity(clubid) do
        Activity
        |> Ecto.Query.where(clubid: ^clubid)
        |> Repo.all

        # activitylist = Enum.each(
        #              fn activity -> 
        #                  {:ok, dt} = activity.inserted_at |> DateTime.from_naive("Etc/UTC")
        #                  ct = DateTime.to_unix dt

        #                  {:ok, dt} = activity.starttime |> DateTime.from_naive("Etc/UTC")
        #                  st = DateTime.to_unix dt

        #                  {:ok, dt} = activity.endtime |> DateTime.from_naive("Etc/UTC")
        #                  et = DateTime.to_unix dt

        #                  %{usrid: activity.usrid, clubid: activity.clubid, cretetime: ct,
        #                     title: activity.title, starttime: st, endtime: et, place: activity.place,
        #                     content: activity.content, attachment: activity.attachmentid}

        #                  end)
        # {:ok, %{activitylist: activitylist} }
    end

    def delete_activity(id) do
        case get_info_activity(id) do
            nil ->
                {:error, "not exist!"}
            activity ->
                case Repo.delete(activity) do
                    {:ok, _ } ->
                        {:ok, "删除成功"}
                    {:error, _ } ->
                        {:error, "删除失败"}
                end
        end
    end
end